//
//  JXWCategoryViewController.m
//  JXWShopping4IPhone
//
//  Created by zheng ji on 14-1-24.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "JXWCategoryViewController.h"
#import "MobClick.h"
#import "Constants.h"
#import "CommonConfigUtil.h"
//#import "CJSONDeserializer.h"
//#import "ProdListController.h"
@interface JXWCategoryViewController ()
{
    
}
@end

@implementation JXWCategoryViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.indicatorView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.indicatorView.autoresizingMask=UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin;
    [self.indicatorView sizeToFit];
   // self.indicatorView.hidden=YES;
    
    
   self.indicatorView.frame=CGRectMake(self.view.center.x,self.view.center.y  , 30, 30);
    
    
    [self.view addSubview:self.indicatorView];
    [self.indicatorView startAnimating];
    
    
    [self initCategoryData];
    
    [self.indicatorView stopAnimating];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
/**
 初始化类别数据
 */
-(void)initCategoryData{
    NSString* localCategoryFile=[NSString stringWithFormat:@"%@/jxwCategory.json",[CommonConfigUtil getFileLocalPath] ];
    if([CommonConfigUtil existFileWithLocalPath:localCategoryFile]){
        
        
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localCategoryFile error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                 //从网络获取分类
                [self getCategoryFromNet];
            }else{
                //从本地获取分类
                [self parseCategory:[NSData dataWithContentsOfFile:localCategoryFile]];
            }
        }else{
            //从网络获取
            [self getCategoryFromNet];
        }

        
        
    }else{
        //从网络获取分类
        [self getCategoryFromNet];
    }
}
/**
 从网络获取分类数据
 */
-(void)getCategoryFromNet{
    /*
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/materialtag/list/?coverid=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getCoverId]];
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    [url release];
    [request release];
    */
    UIApplication* uiApp=[UIApplication sharedApplication];
    uiApp.networkActivityIndicatorVisible=YES;
    
     NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/materialtag/list/?coverid=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getCoverId]];
     NSData *reData=[NSData dataWithContentsOfURL:[ NSURL URLWithString:url]];
    
    [self parseCategory:reData];
    uiApp.networkActivityIndicatorVisible=NO;
    reData=nil;
    
//       [pool release];
    
}
/**
 解析分类数据
 */
-(void)parseCategory:(NSData*) jsonData{
    NSError *error=nil;
 //   CJSONDeserializer *jsondeserializer=[[CJSONDeserializer alloc]init];
    
   // NSDictionary *dictionary=[jsondeserializer deserialize:jsonData error:&error];
    
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
    
    if(!error){
        
         self.categoryArray=[dictionary objectForKey:@"materialGenreList"];
    }
    if(jsonData !=nil){
        @try {
            NSString* localCategoryFile=[NSString stringWithFormat:@"%@/jxwCategory.json",[CommonConfigUtil getFileLocalPath] ];

            [jsonData writeToFile:localCategoryFile atomically:YES];
        }
        @catch (NSException *exception) {
            NSLog(@"create local category file error");
        }
        
    }

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
 
    if(self.categoryArray !=nil)
    return self.categoryArray.count;
    
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.categoryArray !=nil && self.categoryArray.count>=section){
        NSArray *subGenreListArray=[[self.categoryArray objectAtIndex:section]  objectForKey:@"materialList"];
        if(subGenreListArray !=nil) return subGenreListArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"reuse_CategoryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if(self.categoryArray !=nil && self.categoryArray.count>=indexPath.section){
         NSArray *subGenreListArray=[[self.categoryArray objectAtIndex:indexPath.section]  objectForKey:@"materialList"];
        if(subGenreListArray !=nil){
           
           NSString* catetoryName= [[subGenreListArray objectAtIndex:indexPath.row] objectForKey:@"name"];
           NSRange range= [catetoryName rangeOfString:@"#"];
            if(range.length>0){
                cell.textLabel.text=[catetoryName substringToIndex:range.location  ];
                cell.detailTextLabel.text=[catetoryName substringFromIndex:range.location +1];
            }else{
                cell.textLabel.text=catetoryName;
                 cell.detailTextLabel.text=@"";
            }
            NSString* tagID= [[subGenreListArray objectAtIndex:indexPath.row] objectForKey:@"id"];
            cell.tag=[tagID intValue];
          
            
        }
       
    }
    
    //cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSString* categoryName=@"";
   if(self.categoryArray !=nil && self.categoryArray.count>=section){
        
         categoryName= [[self.categoryArray objectAtIndex:section] objectForKey:@"name"];
        
    }
    
    UILabel* lblHeader=[[UILabel alloc] init];
    
    lblHeader.textColor=[UIColor blueColor];
    lblHeader.backgroundColor=[UIColor colorWithRed:192.0/255.0f green:192.0f/255.0f blue:192.0f/255.0f alpha:0.5];
    lblHeader.text=categoryName;
    return lblHeader;

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.categoryArray !=nil && self.categoryArray.count>=indexPath.section){
        NSArray *subGenreListArray=[[self.categoryArray objectAtIndex:indexPath.section]  objectForKey:@"materialList"];
        if(subGenreListArray !=nil){
            
            NSString* materialid= [[subGenreListArray objectAtIndex:indexPath.row] objectForKey:@"id"];
              NSString* catetoryName= [[subGenreListArray objectAtIndex:indexPath.row] objectForKey:@"name"];
            
            NSRange range= [catetoryName rangeOfString:@"#"];
            if(range.length>0){
                catetoryName=[catetoryName substringToIndex:range.location  ];
                
            }
            [self.categoryProtocol catetorySelected:materialid categoryName:catetoryName];
           // [self.segmentController showCategoryProducts:materialid categoryName:catetoryName];

            
        }
    }
    
    [self.categoryPopoverController dismissPopoverAnimated:YES];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [MobClick beginLogPageView:@"categoryView"];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick endLogPageView:@"categoryView"];
   
    
    
}

 

@end
